const express = require("express");
const mysql = require("mysql");
// 创建
const app = express();
// 创建数据库连接
const db = mysql.createPool({
  // 数据库IP地址
  host: "127.0.0.1",
  // 数据库用户名
  user: "root",
  // 数据库密码
  password: "root",
  // 数据库
  database: "node",
});
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// 测试
app.get("/user", (req, res) => {
  db.query("select * from user", (err, result) => {
    if (err) {
      return res.send({ code: 999, msg: err, data: null });
    }
    res.send({ code: 0, msg: "查询成功", data: result });
  });
});
app.post("/user", (req, res) => {
  console.log(req.body);
  db.query(
    `insert into user(id,name,password) value(${req.body.id},"${req.body.name}","${req.body.password}")`,
    (err, result) => {
      if (err) return res.send({ code: 999, msg: err });
      if (result.affectedRows > 0) {
        return res.send({ code: 0, msg: "添加成功" });
      } else {
        return res.send({ code: 5000, msg: "添加失败" });
      }
    }
  );
});
app.delete("/user", (req, res) => {
  db.query(`delete from user where id=${req.body.id}`, (err, result) => {
    if (err) return res.send({ code: 888, msg: err });
    if (result.affectedRows > 0) {
      return res.send({ code: 0, msg: "删除成功" });
    } else {
      return res.send({ code: 5000, msg: "删除失败" });
    }
  });
});
app.put("/user", (req, res) => {
  // const a = req.body.password ? req.body.password : "";
  // const b = req.body.name ? req.body.name :;
  // return console.log(req);
  
  // db.query(
  //   `update user set ? where id=${req.body.id}`,
  //   { name: b, password: a },
  //   (err, result) => {
  //     if (err) return res.send({ code: 888, msg: err });
  //     if (result.affectedRows > 0) {
  //       return res.send({ code: 0, msg: "删除成功" });
  //     } else {
  //       return res.send({ code: 5000, msg: "删除失败" });
  //     }
  //   }
  // );
});
app.post("/login", (req, res) => {
  res.send("用户登录");
});
// 启动
app.listen(3000, () => {
  console.log("项目启动了");
});
